<template>
	<u-popup v-model="showSelf" mode="bottom" border-radius="14" :closeable="true" :safe-area-inset-bottom="true"
		@close="onClose">
		<view class="bg-white spec-contain">
			<view class="spec-header row">
				<!-- 				<custom-image 
                  class="goods-img mr20" 
                  radius="10rpx" 
                  :src="goodsInfo.image" 
                  @tap="previewImage(goodsInfo.image)" 
                /> -->
				<!-- #ifndef MP-ALIPAY -->
				<custom-image class="goods-img mr20" radius="10rpx" @tap="previewImage(goods.image)"
					:src="goods.image" />
				<!-- #endif -->

				<!-- #ifdef MP-ALIPAY -->
				<image :src="goods.image" mode="widthFix"
					style="width: 200rpx; height: 200rpx;margin-right: 20rpx;"
					@tap="previewImage(goods.image)" />
				<!-- #endif -->


				<view class="goods-info flex1">
					<view class="ornament row" style="margin-top: 50rpx;">
						<!-- <text class="lg" style="font-size: 26rpx;">劵后价</text> -->
						<price-format :first-size="46" :second-size="32" :subscript-size="32"
							:price="checkedGoods.rent_price" :weight="500" />
						<!-- <text class="lg">/天</text> -->
					</view>

					<view style="margin-top: 10rpx;">
						<!-- <view class="sm" v-show="showStock">
                        	库存：{{ checkedGoods.stock || '0' }}件
                        </view> -->
						<view class="sm muted">
							<!-- <text>已选择：{{ specInfo.spec_value_str }} {{ form.goodsNum }}件</text> -->
							<text>{{specValueText}}</text>
						</view>
					</view>
				</view>

			</view>
			<!-- 			<view class="flex-row-space-between">
				<view class="flex-column-center" style="width: 50%;">
					<view class="first_return_price">
						￥{{checkedGoods.rent_price}}
					</view>
					<view class="first_title">
						现价
					</view>
				</view>
				<view class="flex-column-center" style="width: 50%;">
					<view class="first_return_price">
						￥{{checkedGoods.market_price}}
					</view>
					<view class="first_title">
						原价
					</view>
				</view>
				<view class="flex-column-center" style="width: 33.33%;">
					<view class="first_return_price">
						￥{{checkedGoods.rent_price}}
						
					</view>
					<view class="first_title">
					总租金
					</view>
				</view>
			</view>
			<view class="line">

			</view> -->



			<view class="spec-main">
				<scroll-view style="max-height: 600rpx;" scroll-y="true">
					<view class="spec-list">
						<!-- 租期 -->
						<view class="spec">
							<view class="name mb20">租赁方式</view>
							<view class="">

							</view>
							<view class="row wrap">
								<view v-for="(item, index) in list" :key="index" @click="itemClick(index)">
									<view class="spec-item2">
										<view class=""
											:class="'spec-item sm ' + ( indexs == index + 1 ? 'checked' : '' )">
											{{ item.name }}
										</view>
										<!-- <image v-if="index==1" class="label" src="/static/common/label.png" mode="scaleToFill"></image> -->
									</view>
								</view>
							</view>
						</view>
						<view class="spec" v-if="goods.price <= 11.6">
							<view class="name mb20">克重</view>
							<view class="row wrap">
								<view v-for="(item, index) in glist" :key="index" @click="itemClickG(index)">
									<view class="spec-item2">
										<view class=""
											:class="'spec-item sm ' + ( gIndexs == index + 1 ? 'checked' : '' )">
											{{ item.name }}
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="spec" v-if="goods.price <= 11.6">
							<view class="name mb20">用途</view>
							<view class="row wrap">
								<view v-for="(item, index) in typelist" :key="index" @click="itemClickType(index)">
									<view class="spec-item2">
										<view class=""
											:class="'spec-item sm ' + ( typeIndexs == index + 1 ? 'checked' : '' )">
											{{ item.name }}
										</view>
									</view>
								</view>
							</view>
						</view>

						<!-- 规格 -->
						<!-- 						<view v-for="(item, index) in specList" :key="index" class="spec">
							<view class="name mb20">{{ item.name }}</view>
							<text
								class="primary xs mb10">{{checkedGoods.spec_value_ids_arr[index] == '' ? '请选择'+item.name:''}}</text>
							<view class="row wrap">
								<view v-for="(specitem, index2) in item.spec_value" :key="index2"
									@click="choseSpecItem(index, index2)">
									<view class="spec-item2">
										<view class="" :class="'spec-item sm ' +
								    ( checkedGoods.spec_value_ids_arr[index] == specitem.id  ? 'checked' : '' ) + 
								    ( isDisable(specitem.id) ? 'disabled':'')">
											{{ specitem.value }}
										</view>
										<image v-if="specitem.value=='租完即送'" class="label"
											src="/static/common/label.png" mode="scaleToFill"></image>
									</view>
								</view> -->
						<!-- 	<view v-for="(specitem, index2) in item.spec_value" :key="index2" :class="'spec-item sm ' +
								    ( checkedGoods.spec_value_ids_arr[index] == specitem.id  ? 'checked' : '' ) + 
								    ( isDisable(specitem.id) ? 'disabled':'')" @click="choseSpecItem(index, index2)">
									{{ specitem.value }}
								</view> -->
						<!-- 							</view>
						</view> -->

						<!-- 租期 -->
						<!--        <view class="spec">
                            <view class="name mb20">租期</view>
                            <view class="row wrap">
                                <view 
                                  v-for="(item, index) in periods" 
                                  :key="item.periods_id" 
                                  :class="'spec-item sm ' + ( item.periods_id == period.periods_id ? 'checked' : '' )"
                                  @tap="chosePeriodsItem(item)">
                                    {{ item.name }}
                                </view>
                            </view>
                        </view> -->

						<!-- 租期 -->
						<!-- 						<view v-if='goodsInfo.serviceList.length' class="spec">
							<view class="name mb20">碎屏保障(推荐选购)</view>
							<view class="wrap">
								<view v-for="(item, index) in goodsInfo.serviceList" @click="itemClick1(index)">
									<view class="spec-item2">
										<view class="flex-row-space-between"
											:class="'spec-item1 sm ' + ( indexs1 == index ? 'checked' : '' )">
											<text>{{ item.s_name }}</text>
											<text>¥{{ item.price }}</text>
										</view>
										<image class="label1" src="/static/common/label1.png" mode="scaleToFill">
										</image>
									</view>
								</view>
							</view>
						</view> -->
					</view>

					<!-- 保险 -->
					<!-- <template v-if="goodsInfo.insurance !== null">
							<view class="spec">
								<view class="name mb20">
									<text>保险套餐</text>
									<text class="muted ml20 xs">可选</text>
								</view>
								<view class="row wrap">
									<view 
									  class="spec-item sm"
									  :class="{ checked: isInsurance }"
									  @tap="isInsurance = !isInsurance;"
									>
										<text>一次性结清</text>
										<text>￥{{ goodsInfo.insurance || '0.00' }}</text>
									</view>
								</view>
							</view>							
						</template> -->
				</scroll-view>
			</view>
			<view class="btns row-between bg-white"
				:class="indexs != 0 && (gIndexs != 0 || goods.price > 11.6) && (typeIndexs != 0 || goods.price > 11.6) ? '':'disabled'">
				<!-- :class="specValueText.indexOf('请选择') != -1 || checkedGoods.stock == 0 ? 'disabled':''" -->
				<!-- #ifndef MP-ALIPAY -->
				<button class="bottomButton flex-column-center" size="lg" @tap="onConfirm">{{ buttonTxt }}</button>
				<!-- #endif -->
				<!-- #ifdef MP-ALIPAY -->
				<view class="bottomButton flex-column-center" size="lg" @tap="onConfirm">{{ buttonTxt }}</view>
				<!-- <view v-if="showConfirm" class="bg-primary br60 white btn alipay-btn" size="lg" @tap="onClick('confirm')">确定</view> -->
				<!-- #endif -->
			</view>
		</view>
	</u-popup>
</template>

<script>
	export default {
		props: {
			show: {
				type: Boolean
			},
			goods: {
				type: Object,
				required: true
			},
			buttonTxt: {
				type: String,
				default: "立即购买"
			},
			showStock: {
				type: Boolean,
				default: true
			},
			disabledNumberBox: {
				type: Boolean,
				default: false
			},
		},

		data() {
			return {
				config: {},
				indexs1: 666,
				indexs: 0,
				gIndexs: 0,
				typeIndexs: 0,
				typeState: false,
				list: [{
					name: '先用后付 按日付租 到期购买/退还',
				}],
				glist: [{
					name: '约20g',
				}],
				typelist: [{
					name: '婚庆佩戴',
				}, {
					name: '宴会佩戴',
				}, {
					name: '聚会佩戴',
				}, {
					name: '业务佩戴',
				}, {
					name: '日常佩戴',
				}, {
					name: '其他',
				}, ],
				showSelf: false, // 是否显示自身Popup

				goodsInfo: {}, // 商品信息
				specList: [], // 规格列表
				goodsItem: [], // 商品规格相应的信息
				periods: [], // 分期列表
				isInsurance: true, // 保险套餐

				// 表单数据
				form: {
					goodsNum: 1, // 商品数量
					period: {}, // 选中分期
					specs: [], // 已选中的规格
					insurance: 0, // 保险套餐
				},

				checkedGoods: {
					stock: 0
				}, //选中的
				outOfStock: [], // 缺货的
				disable: [], // 不可选择的
				goodsNum: 1,
				period: {}, // 选中分期
			};
		},
		created() {
			this.config = uni.getStorageSync('config')
			if (Number(this.config.types) == 2) {
				this.list = [
					{
						name: '全额',
					}
				]
			}
		},
		mounted() {
			this.indexs = 0
			this.gIndexs = 0
			this.typeIndexs = 0
		},
		computed: {

			// first_return_price(){
			// 	const goods = this.checkedGoods;
			// 		const period = this.period;

			// 		var price1=goods.first_return_price

			// 	const price = price1/period.periods;


			// 	return Number(price.toString().match(/^\d+(?:\.\d{0,2})?/));
			// },
			// 价格
			price() {
				const goods = this.checkedGoods;

				//            const period = this.period;

				// var price1=goods.first_rent_price
				// if(Number(period.day)==180){
				// 	price1=goods.second_rent_price
				// }
				// if(Number(period.day)==270){
				// 	price1=goods.third_rent_price
				// }
				// if(Number(period.day)==365){
				// 	price1=goods.four_rent_price
				// }
				//            const price = price1/period.day;


				// return Number(price.toString().match(/^\d+(?:\.\d{0,2})?/));
				return goods.day_price;
			},

			// 根据规格获取对应的信息
			specInfo() {
				let IDList = '';
				const specs = this.form.specs;
				specs.forEach(item => IDList += item.id + ',');
				const IDS = IDList.substring(0, IDList.length - 1);
				return this.goodsItem.find(item => item.spec_value_ids === IDS) || {};
			},


			// 选择的规格参数等
			specValueText() {
				let arr = this.checkedGoods.spec_value_ids?.split(',');
				let spec_str = ''
				if (arr)
					arr.forEach((item, index) => {
						if (item == '') spec_str += this.specList[index].name + ','
					})
				if (this.checkedGoods?.stock != null && spec_str == "")
					return `已选择 ${this.checkedGoods.spec_value_str} ${this.goodsNum} 件`
				else
					return `请选择 ${spec_str.slice(0, spec_str.length - 1)}`
			}
		},

		watch: {
			//         // 数据初始化
			//     	goods(value) {
			//             this.goodsInfo = value;
			//             this.periods = value.goods_periods.periods || [];
			//             this.specList = value.goods_spec || [];
			//             this.goodsItem = value.goods_item || [];
			//             this.$set(this.form, 'period', this.periods[0]);
			//             this.$set(this.form, 'insurance', value.insurance);
			//             this.specList.forEach((item, index) => {
			//                 this.$set(this.form.specs, index, item.spec_value[0]);
			//             });
			//     	},

			goods(value) {
				this.goodsInfo = value;
				if (this.goodsInfo.serviceList.length) {
					this.indexs1 = 0
				} else {
					this.indexs1 = 666
				}

				this.periods = value.goods_periods.periods || [];
				this.period = this.periods[0]

				this.specList = value.goods_spec || [];
				let goodsItem = value.goods_item || [];
				this.outOfStock = goodsItem.filter(item => item.stock == 0)
				// 找出库存不为0的
				const resultArr = goodsItem.filter(item => item.stock != 0)
				if (resultArr.length != 0) {
					resultArr[0].spec_value_ids_arr = resultArr[0].spec_value_ids.split(',');
					this.checkedGoods = resultArr[0]
					if (this.gIndexs != 0) {
						this.checkedGoods.rent_price =  this.checkedGoods.rent_price * 20
					}
				} else {
					// 无法选择
					goodsItem[0].spec_value_ids_arr = []
					this.disable = goodsItem.map(item => item.spec_value_ids.split(','));
					this.checkedGoods = goodsItem[0]
					if (this.gIndexs != 0) {
						this.checkedGoods.rent_price =  this.checkedGoods.rent_price * 20
					}
				}
			},

			specList(value) {
				if (this.checkedGoods.stock == 0) return

				const res = this.goods.goods_item.filter(item => {
					return this.checkedGoods.spec_value_ids === item.spec_value_ids
				})

				// 库存为0的规格
				const idsArr = this.checkedGoods.spec_value_ids_arr;
				const outOfStock = this.outOfStock;
				// 找出规格相同和规格不相同的余数
				const getArrGather = this.getArrResult(idsArr, outOfStock);
				// 计算出缺货的规格项
				this.disable = this.getOutOfStockArr(getArrGather, idsArr)

				if (res.length != 0) {
					let result = JSON.parse(JSON.stringify(res[0]))
					result.spec_value_ids_arr = result.spec_value_ids.split(',')
					this.checkedGoods = result;
					// 同步到父组件
					this.$emit('change', {
						detail: this.checkedGoods
					});
				}
			},

			show(val) {
				this.showSelf = val
			}
		},

		methods: {
			itemClick(index) {
				if (this.indexs == index + 1) {
					this.indexs = 0
				} else {
					this.indexs = index + 1
				}
			},
			itemClickG(index) {
				if (this.gIndexs == index + 1) {
					this.gIndexs = 0
					this.checkedGoods.rent_price =  this.checkedGoods.rent_price / 20
				} else {
					this.gIndexs = index + 1
					this.checkedGoods.rent_price =  this.checkedGoods.rent_price * 20
				}
			},
			itemClickType(index) {
				if (this.typeIndexs == index + 1) {
					this.typeIndexs = 0
				} else {
					this.typeIndexs = index + 1
				}
			},

			itemClick1(index) {
				if (this.indexs1 == index) {
					this.indexs1 = 666
				} else {
					this.indexs1 = index
				}

			},
			// 选择期数
			chosePeriodsItem(item) {
				this.period = item
			},

			isDisable(e) {
				const res = this.disable.filter(item => item == e)
				if (res.length != 0) return true
				else return false
			},

			onClose() {
				this.$emit('close')
			},

			onConfirm(type) {
				// let {
				// 	checkedGoods,
				// 	goodsNum
				// } = this;
				// if (this.specValueText.indexOf('请选择') != -1) return this.$toast({
				// 	title: this.specValueText
				// })
				// if (checkedGoods.stock == 0) return this.$toast({
				// 	title: '当前选择库存不足'
				// })
				// checkedGoods.goodsNum = goodsNum;
				// this.$emit(type, {
				// 	detail: checkedGoods,
				// 	insurance: this.isInsurance ? this.goods.safe_package : null
				// });
				var pay_type = this.indexs ? '2' : '1'
				if (Number(this.config.types) == 2) {
					pay_type = '2'
				}
				if(this.indexs == 0){
					return this.$toast({
					  title: '请选择租赁方式'
					});
				}
				if(this.gIndexs == 0 && this.goods.price <= 11.6){
					return this.$toast({
					  title: '请选择克重'
					});
				}
				if(this.typeIndexs == 0 && this.goods.price <= 11.6){
					return this.$toast({
					  title: '请选择用途'
					});
				}
				this.$emit('confirm', {
					goods: [{
						pay_type: 1,
						service_id: this.indexs1 == 666 ? 0 : this.goodsInfo.serviceList[this.indexs1].id,
						lease_goods_id: this.goodsInfo.id, // 租赁商品ID
						item_id: this.checkedGoods.id, // 租赁型号ID
						goods_num: this.goodsNum, // 租赁数量
						// periods_id: this.period.periods_id,         // 租赁商品租期ID						
					}],
					insurance: this.isInsurance ? this.goodsInfo.insurance : null, // 保险套餐
				});
			},

			// 选择规格
			choseSpecItem(index, index2) {

				const id = this.specList[index].spec_value[index2].id;
				// 无法选择
				const disable = this.disable.filter(item => item == id)
				if (disable.length != 0) return

				let idsArr = this.checkedGoods.spec_value_ids_arr;
				if (id == idsArr[index]) idsArr[index] = ''
				else idsArr[index] = id;
				//保存已选规格
				this.checkedGoods.spec_value_ids_arr = idsArr;
				this.checkedGoods.spec_value_ids = idsArr.join(',');
				// 重新渲染页面
				this.specList = [...this.specList]
			},

			// 过滤出需要进行禁用的规格
			getOutOfStockArr(arr, arr1, result = []) {
				arr.forEach(el => {
					if (el.num >= (arr1.length - 1)) {
						result.push(...el.different)
					}
				})
				return result
			},

			// 匹配出缺货库存和已选中对比结果
			getArrIdentical(arr1, arr2, arr = [], num = 0) {
				arr1.forEach(el => {
					arr2.forEach(el2 => {
						if (el == el2) {
							num += 1;
							arr.push(el)
						}
					})
				});
				return {
					num, //n个相同的
					different: this.getArrDifference([...new Set(arr)].map(Number), arr2.map(Number)),
					identical: [...new Set(arr)]
				}
			},

			// 匹配出已选择和缺库存的
			getArrResult(arr, outOfStock, result = []) {
				outOfStock.forEach(item => {
					const res = this.getArrIdentical(arr, item.spec_value_ids.split(','))
					if (res != undefined && res.length != 0) {
						result.push(res)
					}
				})
				return result
			},

			// 找出两个数组中参数不同的
			getArrDifference(arr1, arr2) {
				return arr1.concat(arr2).filter(function(v, i, arr) {
					return arr.indexOf(v) == arr.lastIndexOf(v);
				});
			},

			// 查看商品图片
			previewImage(current) {
				uni.previewImage({
					current,
					urls: [current] // 需要预览的图片http链接列表
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	.spec-contain {
		border-radius: 10rpx 10rpx 0 0;
		overflow: hidden;
		position: relative;

		.close {
			position: absolute;
			right: 10rpx;
			top: 10rpx;
		}

		.spec-header {
			padding: 30rpx;
			padding-right: 70rpx;
			align-items: flex-start;

			// border-bottom:15rpx solid #F6F9FB ;
			// border: $-solid-border;
			.vip-price {
				margin: 0 24rpx;
				background-color: #FFE9BA;
				line-height: 36rpx;
				border-radius: 6rpx;
				overflow: hidden;

				.price-name {
					background-color: #101010;
					padding: 3rpx 12rpx;
					color: #FFD4B7;
					position: relative;
					overflow: hidden;

					&::after {
						content: '';
						display: block;
						width: 20rpx;
						height: 20rpx;
						position: absolute;
						right: -15rpx;
						background-color: #FFE9BA;
						border-radius: 50%;
						top: 50%;
						transform: translateY(-50%);
						box-sizing: border-box;
					}
				}
			}

			.goods-img {
				width: 180rpx;
				height: 180rpx;
				flex: none;
			}
		}


		.spec-main {
			.spec-list {
				padding: 30rpx 30rpx;

				.spec-item1 {
					line-height: 52rpx;
					width: 100%;
					padding: 0 20rpx;
					background-color: #F4F4F4;
					border-radius: 8rpx;
					margin: 0 20rpx 20rpx 0;
					border: 1px solid #F4F4F4;

					&.checked {
						// background-color: #E8F6FF;
						color: $-color-primary;
						background: rgba(101, 190, 255, 0.1);
						border-color: $-color-primary;
					}

					&.disabled {
						opacity: .5;
						text-decoration: line-through;
					}
				}

				.spec-item {

					line-height: 52rpx;
					padding: 0 20rpx;
					background-color: #F4F4F4;
					border-radius: 8rpx;
					margin: 0 20rpx 20rpx 0;
					border: 1px solid #F4F4F4;

					&.checked {
						// background-color: #E8F6FF;
						color: $-color-primary;
						background: rgba(101, 190, 255, 0.1);
						border-color: $-color-primary;
					}

					&.disabled {
						opacity: .5;
						text-decoration: line-through;
					}
				}
			}
		}

		// 底部按钮无法选择
		.disabled {
			opacity: 0.4;
		}

		.btns {
			height: 120rpx;
			// padding: 0 30rpx;
			// margin-top: 80rpx;

			.add-cart {
				background-color: rgba(36, 163, 255, 0.1);
			}

			.btn {
				margin: 0 10rpx;
				flex: 1;
			}

			.alipay-btn {
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 30rpx;
				text-align: center;
				font-size: 32rpx;
			}
		}
	}

	.bottomButton {
		width: 100%;
		height: 86rpx;
		background: $base-color;
		border-radius: 11rpx 11rpx 11rpx 11rpx;
		opacity: 1;
		font-size: 27rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
	}

	.first_return_price {
		font-size: 27rpx;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		color: #FF5B5B;
	}

	.first_title {
		font-size: 23rpx;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		color: #333333;
	}

	.line {
		margin-top: 30rpx;
		height: 15rpx;
		background: #F6F9FB;
	}

	.spec-item2 {
		position: relative;
	}

	.label1 {
		right: 8rpx;
		top: -15rpx;
		position: absolute;
		width: 104rpx;
		height: 30rpx;
	}

	.label {
		right: 18rpx;
		top: -15rpx;
		position: absolute;
		width: 116rpx;
		height: 30rpx;
	}
</style>